package com.gexiaobao.pigeon.ui.home

import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.App
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.model.bean.AccountUserInfo
import com.gexiaobao.pigeon.app.model.bean.MessageListResponse
import com.gexiaobao.pigeon.app.model.bean.PaymentResponse
import com.gexiaobao.pigeon.app.model.bean.ScanPigeonsResponse
import com.gexiaobao.pigeon.app.model.bean.SigningFileResponse
import com.gexiaobao.pigeon.app.model.bean.UserAuthsInfoResponse
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.DESUtils
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentHomeBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.activity.ActivityGameResult
import com.gexiaobao.pigeon.ui.activity.LoftPayInfoActivity
import com.gexiaobao.pigeon.ui.activity.supervise.ActivitySigning
import com.gexiaobao.pigeon.ui.adapter.MessageListAdapter
import com.gexiaobao.pigeon.ui.breeding_pigeon.ActivityBreedingManagement
import com.gexiaobao.pigeon.ui.breeding_pigeon.ActivityBreedingPigeonManage
import com.gexiaobao.pigeon.ui.breeding_pigeon.ActivityMakePedigreeBooks
import com.gexiaobao.pigeon.ui.dialog.RxDialogShedList
import com.gexiaobao.pigeon.ui.fragment.mine.banking.activity.ActivityAccountTransfer
import com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity.ActivityShedRace
import com.gexiaobao.pigeon.ui.fragment.mine.tools.activity.ActivityRaceProof
import com.gexiaobao.pigeon.ui.home.activity.ActivityIndustrialRegister
import com.gexiaobao.pigeon.ui.pigeoncatcher.ActivityOrderSquare
import com.gexiaobao.pigeon.viewmodel.request.RequestHomeViewModel
import com.google.gson.Gson
import com.google.zxing.BarcodeFormat
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yzq.zxinglibrary.android.CaptureActivity
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import org.json.JSONObject
import javax.crypto.IllegalBlockSizeException


class HomeFragment : BaseFragment<HomeViewModel, FragmentHomeBinding>() {

    private var userId: String = ""
    private var bitmap: Bitmap? = null
    private var isShowMoreTools = true
    private val mAdapter: MessageListAdapter by lazy { MessageListAdapter(arrayListOf()) }
    private var messageData: ArrayList<MessageListResponse.DataList> = arrayListOf()
    private var mAccountUserInfo: AccountUserInfo? = null
    private var title = ""
    private var raceId = 0

    //请求数据ViewModel
    private val requestHomeViewModel: RequestHomeViewModel by viewModels()

    //界面状态管理者
    private lateinit var loadsir: LoadService<Any>

    override fun initView(savedInstanceState: Bundle?) {
        activity?.let { StatusBarUtil.setTransparentForImageViewInFragment(it, mDatabind.rlTitle) }
        mDatabind.viewmodel = mViewModel
        mViewModel.myToolsMore.set(!isShowMoreTools)
        userId = KvUtils.decodeString(Constant.USERID)
        generateQRCode(userId) // 生成二维码并显示
        val swipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val deleteItem = SwipeMenuItem(activity)
                .setBackground(R.drawable.round_b_g_5_train_fly_list_delete_red)
                .setTextColor(Color.WHITE)
                .setText(R.string.delete)
                .setTextSize(15)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(deleteItem)
        }
        mDatabind.swipeRecyclerView.setSwipeMenuCreator(swipeMenuCreator)

        val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
            /** 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱 */
            menuBridge.closeMenu()
            /** 左侧还是右侧菜单 */
//            val direction = menuBridge.direction
//            /**  菜单在Item中的Position */
//            val menuPosition = menuBridge.position
            /** 调用删除接口 */
            showLoading(getString(R.string.loading))
            requestHomeViewModel.deleteMessage(mAdapter.data[position].id.toString())
        }
        mDatabind.swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener)

        mDatabind.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 1f))
        )

        //状态页配置
        loadsir = loadServiceInit(mDatabind.swipeRecyclerView) {
            //点击重试时触发的操作
            loadsir.showLoading()
            requestHomeViewModel.getMessageList(true)
        }

        mDatabind.swipeRefreshLayout.init {
            loadsir.showLoading()
            requestHomeViewModel.getMessageList(true)
            requestHomeViewModel.getUserDetail()
        }

        eventViewModel.headIconResult.observeInFragment(this) {
            if (it) {
                requestHomeViewModel.getUserDetail()
            }
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            if (mAdapter.data[position].messageType == 3) {
                if (mAdapter.data[position].passId == 0) {
                    RxToast.showToast(getString(R.string.No_jump_information))
                    return@setOnItemClickListener
                }
                raceId = mAdapter.data[position].passId
                title = mAdapter.data[position].topic
                if (mAdapter.data[position].passStatus == 4 || mAdapter.data[position].passStatus == 5) {
                    requestHomeViewModel.getMemberNum(mAdapter.data[position].passId.toString())
                } else {
                    startActivity<ActivityGameResult>(
                        "title" to title,
                        "passId" to raceId,
                        "type" to "race"
                    )
                    activity?.overridePendingTransition(
                        android.R.anim.fade_in,
                        android.R.anim.fade_out
                    )
                }
            } else {
                nav().navigateAction(R.id.action_to_notice_detail, Bundle().apply {
                    putInt("id", mAdapter.data[position].id)
                })
            }
        }
        eventViewModel.toNoticeIsCertified.observeInFragment(this) {
            requestHomeViewModel.getUserMemberInfo()
        }
        eventViewModel.toRefreshData.observeInFragment(this) {
            requestHomeViewModel.getUserDetail()
        }
    }

    private fun generateQRCode(userId: String) {
        if (userId.isEmpty()) {
            LogUtils.warnInfo("UserId为空")
            return
        }
        val qrCodeWriter = QRCodeWriter()
        try {
            val bitMatrix = qrCodeWriter.encode(userId, BarcodeFormat.QR_CODE, 240, 240)
            val width = bitMatrix.width
            val height = bitMatrix.height
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)

            val canvas = Canvas(bitmap!!)
            canvas.drawColor(Color.WHITE)

            val paint = Paint()
            paint.isAntiAlias = true
            paint.isFilterBitmap = true
            paint.isDither = true

            for (x in 0 until width) {
                for (y in 0 until height) {
                    bitmap!!.setPixel(x, y, if (bitMatrix[x, y]) Color.BLACK else Color.WHITE)
                }
            }
        } catch (e: WriterException) {
            e.printStackTrace()
        }
    }

    override fun lazyLoadData() {
        loadsir.showLoading()
        requestHomeViewModel.getMessageList(true)
        requestHomeViewModel.getUserDetail()
        requestHomeViewModel.getUserMemberInfo()
    }

    @SuppressLint("CheckResult")
    override fun createObserver() {
        requestHomeViewModel.run {
            memberNumResult.observe(viewLifecycleOwner) {
                if (it != null) {
                    nav().navigateAction(R.id.action_to_sign_up_detail, Bundle().apply {
                        putString("title", title)
                        putString("memberCode", it.memberNum)
                        putInt("id", raceId)
                    })
                }
            }

            messageList.observe(viewLifecycleOwner) {
                if (mDatabind.swipeRefreshLayout.isRefreshing) {
                    mDatabind.swipeRefreshLayout.isRefreshing = false
                }
                if (it.listData?.isEmpty() == false) {
                    messageData.addAll(it.listData)
                }
                loadListData(it, mAdapter, loadsir, mDatabind.swipeRecyclerView, mDatabind.swipeRefreshLayout)
            }

            /** 用户数据 */
            userInfoResult.observe(viewLifecycleOwner) {
                val userIcon = it.iconUrl
                mDatabind.tvManageTheShed.isVisible = it.userAuth

                CacheUtil.setUser(it)
                mViewModel.userName.set(it.name)
//                ImageLoaderManager.loadCircleImageFall(context, userIcon, mDatabind.mineUserHeadIcon, R.mipmap.head_default_icon)

                context?.let { it1 ->
                    Glide.with(it1).asBitmap().load(userIcon)
                        .into(object : CustomTarget<Bitmap>() {

                            override fun onResourceReady(
                                resource: Bitmap,
                                transition: Transition<in Bitmap>?
                            ) {
                            }

                            override fun onLoadCleared(placeholder: Drawable?) {}
                        })
                }
                mDatabind.tvHomePickUpPigeons.isInvisible = !it.carState
            }

            deleteMsgResult.observe(viewLifecycleOwner) {
                dismissLoading()
                if (it.isSuccess) {
                    requestHomeViewModel.getMessageList(true)
                } else {
                    RxToast.showToast(it.errorMsg)
                }
            }

            accountUserInfoResult.observe(viewLifecycleOwner) { resultState ->
                parseState(resultState, {
                    if (it.isIdentityChecked) {
                        KvUtils.encode("isCertified", true)//保存认证状态（认证通过）
                        mDatabind.ivHomeAuthenticationStatus.background = ContextCompat.getDrawable(requireContext(), R.mipmap.icon_in_real_name)
                    } else {
                        KvUtils.encode("isCertified", false)//保存认证状态（认证不通过）
                        mDatabind.ivHomeAuthenticationStatus.background = ContextCompat.getDrawable(requireContext(), R.mipmap.icon_unnamed)
                    }
                    mAccountUserInfo = it
                }, {
                    RxToast.showToast(it.msg)
                })
            }

            userAuthsResult.observe(viewLifecycleOwner) {
                dismissLoading()
                showDialogShedInfo(it)
            }
        }
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mDatabind.tvMineOrganization,
            mDatabind.tvMineMyDevice,
            mDatabind.tvMinePigeon,
            mDatabind.tvMyTraining,
            mDatabind.tvMineMyMessage,
            mDatabind.llMineBanking,
            mDatabind.tvMineMatchLineQuery,
            mDatabind.tvMineVideoTutorial,
            mDatabind.tvMineMinuteSpeed,
            mDatabind.tvHomeFindPigeon,
            mDatabind.tvMineClub,
            mDatabind.tvMineBob,
            mDatabind.tvMineProof,
            mDatabind.llHomeScan,
            mDatabind.tvManageTheShed,
            mDatabind.tvHomePickUpPigeons,
            mDatabind.tvHomeBloodPigeonManage,
            mDatabind.tvHomeBreedingManage,
            mDatabind.tvHomeMakeBloodBook,
            mDatabind.llHomeIndustrial,
//            mDatabind.tvMineFinance
        ) {
            when (it) {
//                mDatabind.tvMineFinance -> startActivity<ActivityWebView>()
                mDatabind.llHomeIndustrial -> startActivity<ActivityIndustrialRegister>()
                mDatabind.tvHomeBloodPigeonManage -> startActivity<ActivityBreedingPigeonManage>()
                mDatabind.tvHomeBreedingManage -> startActivity<ActivityBreedingManagement>("pigeonId" to 0, "intentType" to "rear", "sex" to "")
                mDatabind.tvHomeMakeBloodBook -> startActivity<ActivityMakePedigreeBooks>()
//                mDatabind.llQrcode -> showBigImageDialog(bitmap)
                mDatabind.tvHomePickUpPigeons -> startActivity<ActivityOrderSquare>()
                mDatabind.tvManageTheShed -> {
                    showLoading(getString(R.string.loading))
                    requestHomeViewModel.getUserAuths()
                }

                mDatabind.llHomeScan -> permissionRequest()
                mDatabind.tvMineProof -> startActivity<ActivityRaceProof>()//比赛凭证
                mDatabind.tvMineBob -> nav().navigateAction(R.id.action_mine_to_organization, Bundle().apply {
                    putInt("status", 3)//公棚
                })

                mDatabind.tvMineClub -> nav().navigateAction(R.id.action_mine_to_organization, Bundle().apply {
                    putInt("status", 1)//俱乐部
                })

                mDatabind.tvMineOrganization -> nav().navigateAction(R.id.action_mine_to_organization, Bundle().apply {
                    putInt("status", 2)//协会
                })

                mDatabind.tvMinePigeon -> nav().navigateAction(R.id.action_mine_to_pigeon)
                mDatabind.tvMineMyDevice -> nav().navigateAction(R.id.action_to_my_device)
                mDatabind.tvMyTraining -> nav().navigateAction(R.id.action_to_my_training)
//                mDatabind.tvMineSetting -> nav().navigateAction(R.id.action_to_setting)
                mDatabind.tvMineMyMessage -> nav().navigateAction(R.id.action_to_my_message_list)
                mDatabind.llMineBanking -> startToMineBanking()
                mDatabind.tvMineMatchLineQuery -> nav().navigateAction(R.id.action_to_match_line_query)
                mDatabind.tvMineVideoTutorial -> nav().navigateAction(R.id.action_to_video_tutorial)
                mDatabind.tvMineMinuteSpeed -> nav().navigateAction(R.id.action_to_minute_speed)
//                mDatabind.mineUserHeadIcon -> nav().navigateAction(R.id.action_to_personal_info)
                mDatabind.tvHomeFindPigeon -> nav().navigateAction(R.id.action_to_fragment_find_pigeon)
            }
        }
    }

//    private fun showBigImageDialog(bitmap: Bitmap?) {
//        val dialog = RxDialogBigImage(context)
//        if (bitmap != null) {
//            dialog.setImage(bitmap)
//        }
//        dialog.setFullScreen()
//        dialog.show()
//    }

    private fun showDialogShedInfo(data: UserAuthsInfoResponse) {
        val dialog = RxDialogShedList(context)
        if (!data.isEmpty()) {
            dialog.setAdapterData(data.list)
        }
        dialog.setOnClickListener(object : RxDialogShedList.OnItemClickListener {
            override fun onItemClick(position: Int, id: Int, pair: Int, video: Int) {
                startActivity<ActivityShedRace>("orgId" to id, "type" to 2, "pair" to pair, "video" to video)
                dialog.dismiss()
            }
        })
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun permissionRequest() {
        XXPermissions.with(this)
            .permission(Permission.CAMERA)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(activity, CaptureActivity::class.java)
                    startActivity.launch(intent)
                }
            }
    }

    val startActivity = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.data != null && it.resultCode == RESULT_OK) {
            val content = it.data!!.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
            if (!content.isNullOrEmpty()) {
                try {
                    val result = DESUtils.decryptDES(content)
                    val jsonObject = JSONObject(result)
                    val qrCodeType = jsonObject.getInt("qrCodeType")
                    if (qrCodeType == 1) {
                        val dataScan = Gson().fromJson(result, ScanPigeonsResponse::class.java)
                        if (dataScan != null) {
                            startActivity<LoftPayInfoActivity>("dataBean" to dataScan)
                        }
                    }
                    if (qrCodeType == 2) {
                        val dataScan = Gson().fromJson(result, SigningFileResponse::class.java)
                        if (dataScan != null) {
                            startActivity<ActivitySigning>("url" to dataScan.url)
                        }
                    }
                    if (qrCodeType == 3) {
                        val dataPay = Gson().fromJson(result, PaymentResponse::class.java)
                        if (dataPay != null) {
                            startActivity<ActivityAccountTransfer>("orgId" to dataPay.orgId, "userId" to dataPay.userId)
                        }
                    }
                } catch (e: IllegalBlockSizeException) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun startToMineBanking() {
        if (App.isFirstAccountCheck) {
            if (mAccountUserInfo != null) {
                if (mAccountUserInfo!!.isIdentityChecked
                    && mAccountUserInfo!!.isSignContract
                    && mAccountUserInfo!!.isPhoneChecked
                    && mAccountUserInfo!!.isSetPayPwd
                    && mAccountUserInfo!!.isBindBank
                ) {
                    KvUtils.encode("isCertified", true)//保存认证状态（认证通过）
                    nav().navigateAction(R.id.action_to_my_banking, Bundle().apply {
                        putInt(Constant.INTO_TYPE, 1)//从首页跳入
                    })
                } else {
                    KvUtils.encode("isCertified", false)//保存认证状态（认证不通过）
                    nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
                        putString(Constant.INTO_TYPE, "mine")
                    })
                }
            }
            App.isFirstAccountCheck = false
        } else {
            nav().navigateAction(R.id.action_to_my_banking, Bundle().apply {
                putInt(Constant.INTO_TYPE, 1)//从首页跳入
            })
        }
    }

}